﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Linq;

namespace WpfLibrary1
{
    public enum SessionState { NotStart, Processing, Waiting, End }
    public class Session
    {
        public Guid SessionId { get; private set; }
        public string SessionName { get; set; }
        public SessionState State { get; protected set; }
        protected AutoResetEvent autoResetEvent = new AutoResetEvent(false);
        public WaitHandle GetWaitHandle() { return autoResetEvent; }

        protected object Param { get;   set; }
        public void Start(object param, TimeSpan timeout)
        { 
            autoResetEvent.Reset();
            this.State = SessionState.Waiting;
            if (WaitForComplete(timeout))
            {
                SessionId = Guid.NewGuid();
                this.Param = param;
                this.State = SessionState.Processing;
            }
        }
       

        private IEnumerable<Session> sessions;
        public void SetWaitList(IEnumerable<Session> sessions) { this.sessions = sessions; }
        private bool WaitForComplete(TimeSpan timeout)
        {
            if (sessions == null||sessions.Count()==0) { return true; }
            return WaitHandle.WaitAll(sessions.Select(a => a.GetWaitHandle()).ToArray(), timeout);

        }
        public void End()
        {
            this.autoResetEvent.Set();
            this.State = SessionState.End;
        }
    }
    public class Session<ParmType> : Session
    {
        public void Start(ParmType param, TimeSpan timeout)
        {
            base.Start(param, timeout);
        }


        public new ParmType Param { get { return (ParmType)base.Param; } }








    }
}